package com.example.demo.controller;

import com.example.demo.service.SmartGeneratorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 流式响应控制器
 * 提供Server-Sent Events (SSE) 流式聊天功能
 * 
 * @author Spring AI Demo
 */
@RestController
@RequestMapping("/api/stream")
@CrossOrigin(origins = "*")
public class StreamController {

    private static final Logger logger = LoggerFactory.getLogger(StreamController.class);

    private final SmartGeneratorService smartGeneratorService;

    public StreamController(SmartGeneratorService smartGeneratorService) {
        this.smartGeneratorService = smartGeneratorService;
    }

    /**
     * 流式聊天API
     * 使用Server-Sent Events (SSE) 实现实时流式响应
     * 
     * @param message 用户消息
     * @return 流式响应
     */
    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@RequestParam String message) {
        logger.info("收到流式聊天请求：{}", message);
        
        return smartGeneratorService.streamChat(message)
                .filter(chunk -> chunk != null && !chunk.trim().isEmpty()) // 过滤空内容
                .doOnNext(chunk -> logger.debug("原始数据块: '{}'", chunk))
                .map(chunk -> chunk.trim()) // 只清理空白字符
                .filter(chunk -> !chunk.isEmpty()) // 再次过滤空内容
                .concatWith(Flux.just("[DONE]"))
                .doOnSubscribe(subscription -> logger.info("开始流式响应"))
                .doOnComplete(() -> logger.info("流式响应完成"))
                .doOnError(error -> logger.error("流式响应出错", error))
                .onErrorReturn("[ERROR] 流式响应出现错误");
    }

    /**
     * 流式聊天API（JSON格式）
     * 返回JSON格式的流式数据
     * 
     * @param message 用户消息
     * @return JSON格式的流式响应
     */
    @GetMapping(value = "/chat-json", produces = MediaType.APPLICATION_NDJSON_VALUE)
    public Flux<Map<String, Object>> streamChatJson(@RequestParam String message) {
        logger.info("收到JSON流式聊天请求：{}", message);
        
        // 创建完成响应
        Map<String, Object> doneResponse = new HashMap<>();
        doneResponse.put("type", "done");
        doneResponse.put("content", "");
        doneResponse.put("timestamp", System.currentTimeMillis());
        
        // 创建错误响应
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("type", "error");
        errorResponse.put("content", "流式响应出现错误");
        errorResponse.put("timestamp", System.currentTimeMillis());
        
        return smartGeneratorService.streamChat(message)
                .map(chunk -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("type", "chunk");
                    response.put("content", chunk);
                    response.put("timestamp", System.currentTimeMillis());
                    return response;
                })
                .concatWith(Flux.just(doneResponse))
                .doOnSubscribe(subscription -> logger.info("开始JSON流式响应"))
                .doOnComplete(() -> logger.info("JSON流式响应完成"))
                .doOnError(error -> logger.error("JSON流式响应出错", error))
                .onErrorReturn(errorResponse);
    }

    /**
     * 模拟打字机效果的流式响应
     * 
     * @param message 用户消息
     * @return 带延迟的流式响应
     */
    @GetMapping(value = "/typewriter", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> typewriterChat(@RequestParam String message) {
        logger.info("收到打字机效果聊天请求：{}", message);
        
        return smartGeneratorService.streamChat(message)
                .delayElements(Duration.ofMillis(50)) // 添加50ms延迟模拟打字机效果
                .map(chunk -> "data: " + chunk + "\n\n")
                .concatWith(Flux.just("data: [DONE]\n\n"))
                .doOnSubscribe(subscription -> logger.info("开始打字机效果流式响应"))
                .doOnComplete(() -> logger.info("打字机效果流式响应完成"))
                .doOnError(error -> logger.error("打字机效果流式响应出错", error))
                .onErrorReturn("data: [ERROR] 流式响应出现错误\n\n");
    }

    /**
     * 流式响应健康检查
     * 
     * @return 测试流式响应
     */
    @GetMapping(value = "/health", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamHealth() {
        return Flux.interval(Duration.ofSeconds(1))
                .take(5)
                .map(i -> "data: 流式服务正常运行 - " + (i + 1) + "/5\n\n")
                .concatWith(Flux.just("data: [DONE] 健康检查完成\n\n"))
                .doOnSubscribe(subscription -> logger.info("开始流式健康检查"))
                .doOnComplete(() -> logger.info("流式健康检查完成"));
    }

    /**
     * 测试用的简单流式聊天（修复版本）
     * 
     * @param message 用户消息
     * @return 流式响应
     */
    @GetMapping(value = "/chat-fixed", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChatFixed(@RequestParam String message) {
        logger.info("收到修复版流式聊天请求：{}", message);
        
        return smartGeneratorService.streamChat(message)
                .filter(chunk -> chunk != null && !chunk.trim().isEmpty())
                .doOnNext(chunk -> logger.debug("修复版数据块: '{}'", chunk))
                .map(chunk -> chunk.trim())
                .filter(chunk -> !chunk.isEmpty())
                .concatWith(Flux.just("[DONE]"))
                .doOnSubscribe(subscription -> logger.info("开始修复版流式响应"))
                .doOnComplete(() -> logger.info("修复版流式响应完成"))
                .doOnError(error -> logger.error("修复版流式响应出错", error))
                .onErrorReturn("[ERROR] 修复版流式响应出现错误");
    }

    /**
     * 获取流式API使用说明
     * 
     * @return 使用说明
     */
    @GetMapping("/info")
    public Map<String, Object> getStreamInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("description", "Spring AI DeepSeek 流式响应服务");
        info.put("endpoints", new String[]{
            "GET /api/stream/chat?message=你好 - 基础流式聊天",
            "GET /api/stream/chat-fixed?message=你好 - 修复版流式聊天",
            "GET /api/stream/chat-json?message=你好 - JSON格式流式聊天",
            "GET /api/stream/typewriter?message=你好 - 打字机效果流式聊天",
            "GET /api/stream/health - 流式服务健康检查"
        });
        info.put("usage", "使用curl测试: curl -N 'http://localhost:8080/api/stream/chat-fixed?message=你好'");
        info.put("browser", "浏览器访问: http://localhost:8080/api/stream/chat-fixed?message=你好");
        info.put("contentType", "text/event-stream");
        return info;
    }
} 